//
//  RecommendDetailViewController.m
//  PlayerFix
//
//  Created by DAT on 15/11/5.
//  Copyright © 2015年 DAT. All rights reserved.
//

#import "RecommendDetailViewController.h"
#import <UIImageView+WebCache.h>
#import "RecommendModel.h"
#import "UIImage+Blur.h"
#import "DATAsyncGetAFNBlock.h"



@interface RecommendDetailViewController ()

@property (nonatomic, strong) UIImageView *coverImg;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) UIButton *lastButton;
@property (nonatomic, strong) UISlider *playSlider;
@property (nonatomic, strong) UILabel *currentTime;
@property (nonatomic, strong) UILabel *totalTime;
@property (nonatomic, strong) NSTimer *myTimer; //定时器  轮播标题


@property (nonatomic,strong)CABasicAnimation *basicAnimation;

@property(nonatomic,strong)UIImageView *imageView;




@end

int indexTwo = 0;

@implementation RecommendDetailViewController

+ (instancetype)shareMusicPlayer{
    
    static RecommendDetailViewController *recommendDetailVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        recommendDetailVC = [[RecommendDetailViewController alloc] init];
    });
    return recommendDetailVC;
}

//懒加载
- (CABasicAnimation *)basicAnimation {
    if (_basicAnimation == nil) {
        self.basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        //旋转一圈时长
        self.basicAnimation.duration = 30;
        //开始动画的起始位置
        self.basicAnimation.fromValue = [NSNumber numberWithInt:0];
        //M_PI是180度
        self.basicAnimation.toValue = [NSNumber numberWithInt:M_PI*2];
        //动画重复次数
        [self.basicAnimation setRepeatCount:NSIntegerMax];
        //播放完毕之后是否逆向回到原来位置
        [self.basicAnimation setAutoreverses:NO];
        //是否叠加（追加）动画效果
        [self.basicAnimation setCumulative:YES];
        //停止动画，速度设置为0
        self.imageView.layer.speed = 1;
        //    self.ImageView.layer.speed = 0;
        [self.imageView.layer addAnimation:self.basicAnimation forKey:@"basicAnimation"];
        
    }
    return _basicAnimation;
}

//视图已经消失时
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    //    [self.player stop];
    indexTwo = 0;
    //    [_myTime invalidate];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [self.imageView.layer removeAllAnimations];//移除动画
        self.basicAnimation = nil;
        [self basicAnimation];//开始动画
        
    }
    if (self.player.state == STKAudioPlayerStatePaused) {
        
        self.basicAnimation = nil;
        
    }
    
}

- (void)setId:(NSString *)Id{
   
    if (_Id != Id) {
        
        _Id = Id;
    }
    [self playMusic];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseBtn.png"] forState:UIControlStateNormal];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSLog(@"IdIdId ************************ %@",self.recommend.Id);
    NSLog(@"arrayarrayarray ********************* %ld", self.allListArray.count);
    
    //返回图标
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"backBtn.png"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 30 , 30 );
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    [button addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];

    
    
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    //下面的初始化也可以,但设置不了enableVolumeMixer,就无法调节音量
    //self.player = [[STKAudioPlayer alloc] init];
    //self.player.delegate = self;
    self.player.volume = 0.5;

    
    self.coverImg = [[UIImageView alloc] initWithFrame: CGRectMake(48 , 48, 283, 283)];
    self.coverImg.backgroundColor = [UIColor clearColor];
    self.coverImg.image = [UIImage imageNamed:@"holderPic_recommend.png"];
    self.coverImg.layer.masksToBounds = YES;
    self.coverImg.layer.cornerRadius = 283 / 2;
    [self.view addSubview:self.coverImg];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 , 386, 375, 60)];
    self.titleLabel.backgroundColor = [UIColor clearColor];
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:self.titleLabel];

    self.playSlider = [[UISlider alloc] initWithFrame:CGRectMake(35, 430 ,305, 20)];
    self.playSlider.minimumTrackTintColor = [UIColor grayColor];
    self.playSlider.maximumTrackTintColor = [UIColor lightGrayColor];
    [self.playSlider addTarget:self action:@selector(progressSender) forControlEvents:UIControlEventValueChanged];
    //[self.playSlider becomeFirstResponder];
    //[self.playSlider setThumbImage:[UIImage imageNamed:@"iconfont-yuanquan-2.png"] forState:UIControlStateNormal];
    [self.playSlider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:self.playSlider];
    
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    [self.view addSubview:bgImageView];
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.playButton];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseBtn.png"] forState:UIControlStateNormal];
    self.playButton.frame = CGRectMake(345/2 , 500 , 30 , 30 );
    [self.playButton addTarget:self action:@selector(playButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.nextButton setBackgroundImage:[UIImage imageNamed:@"nextPlayer.png"] forState:UIControlStateNormal];
    [self.view addSubview:self.nextButton];
    self.nextButton.frame = CGRectMake(345/2  + 61 , 505 , 20 , 20 );
    [self.nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.lastButton setBackgroundImage:[UIImage imageNamed:@"lastPlayer.png"] forState:UIControlStateNormal];
    [self.view addSubview:self.lastButton];
    self.lastButton.frame = CGRectMake(345/2 - 53 , 505 , 20 , 20 );
    [self.lastButton addTarget:self action:@selector(lastButton:) forControlEvents:UIControlEventTouchUpInside];

    self.currentTime = [[UILabel alloc] initWithFrame:CGRectMake((375 - 200) / 2 ,400 , 100 , 30)];
    [self.view addSubview:self.currentTime];
    self.currentTime.textColor = [UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1.0];
    self.currentTime.font = [UIFont systemFontOfSize:14];
    //    [_currentTime release];
    //self.currentTime.textColor = [UIColor whiteColor];
    self.currentTime.font = [UIFont systemFontOfSize:14];
    
    self.totalTime = [[UILabel alloc]initWithFrame:CGRectMake((375 - 200) / 2 ,400 , 100 , 30 )];
    [self.view addSubview:self.totalTime];
    self.totalTime.textColor = [UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1];
    self.totalTime.font = [UIFont systemFontOfSize:12];
    //    [_totalTime release];
    //self.totalTime.textColor = [UIColor whiteColor];
    self.totalTime.font = [UIFont systemFontOfSize:12];
    
    //定时器, 轮播标题
    //self.myTime = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeWork) userInfo:nil repeats:YES];

    
    //UIImage *image = [UIImage imageNamed:@"111.jpg"];
    //imageView.image = [image boxblurImageWithBlur:1];
    
//    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(60 , 150 , 250 , 250 )];
//    self.imageView.layer.masksToBounds = YES;
//    self.imageView.layer.cornerRadius = 125 ;
//    [self.view addSubview:self.imageView];

    
    
    
}

- (void)playButton:(UIButton *)btn{
    
    if (self.player.state == STKAudioPlayerStatePaused) {
        
        //        //NSLog(@"暂停");
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseBtn.png"] forState:UIControlStateNormal];
        [self.player resume];//继续
        //开始旋转
        //得到view当前动画时间偏移量
        CFTimeInterval stopTime = [self.imageView.layer timeOffset];
        //初始化开始时间
        self.imageView.layer.beginTime = 0;
        //初始化时间偏移量
        self.imageView.layer.timeOffset = 0;
        //设置动画速度
        self.imageView.layer.speed = 1;
        //计算时间差
        CFTimeInterval tempTime = [self.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
        //重新设置动画开始时间
        self.coverImg.layer.beginTime = tempTime;
        
    }else if (self.player.state == STKAudioPlayerStatePlaying) {
        
        //        //NSLog(@"播放");
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"playBtn.png"] forState:UIControlStateNormal];
        [self.player pause];
        CFTimeInterval stopTime = [self.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        //停止动画，速度设置为0
        self.imageView.layer.speed = 0;
        //设置时间偏移量
        self.imageView.layer.timeOffset = stopTime;
        
    }else
    {
        [self playMusic];
    }

}

- (void)backButtonAction{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)nextButtonAction:(UIButton *)btn{
    
    self.indexRow++;
    //如果点击的下标大于数组个数 为0 代码保护
    if (self.indexRow == self.allListArray.count) {
        
        self.indexRow = 0;
    }
    [self.player pause];
    RecommendModel *recommend = [self.allListArray objectAtIndex:self.indexRow];
//    self.song_id = singleM.trackId;
//    self.coverImage = singleM.coverLarge;
    [self.coverImg sd_setImageWithURL:[NSURL URLWithString:recommend.pic]];
    //    [self playMusic];
    indexTwo = 0;
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseBtn.png"] forState:UIControlStateNormal];

}

- (void)lastButton:(UIButton *)btn{
    
    //    [self.player stop];
    //    [self.player clearQueue];//清空音频队列
    //    [self.timer invalidate];//定时器停止
    //    self.timer = nil;
    //    self.progressSlider.value = 0.f;
    //    [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
    //    self.timeLabel.text = [NSString stringWithFormat:@"00:00 / %02ld:%02ld" , self.durMin, self.durSec];
    self.indexRow -- ;
    //如果小于0 从最后一首开始
    if (self.indexRow < 0) {
        
        self.indexRow = self.allListArray.count - 1;
    }
    [self.player pause];
    RecommendModel *recommend = [self.allListArray objectAtIndex:self.indexRow];
    //self.song_id = singleM.trackId;
    //self.coverImg = recommend.pic;
    [self.coverImg sd_setImageWithURL:[NSURL URLWithString:recommend.pic]];
    //    [self playMusic];
    indexTwo = 0;
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pauseBtn.png"] forState:UIControlStateNormal];

}

- (void)progressSlider:(UISlider *)slider{
    
    if (self.player) {
        
        [self.player seekToTime:slider.value];
    }
}

- (void)playMusic
{
    
    
    [self.imageView.layer removeAllAnimations];
    _basicAnimation = nil;
    self.imageView.image = [UIImage imageNamed:@"F0AB9D064E5D1695CB1857176EBE14A6"];
    [self.player pause];
    
    [self.player play:self.recommend.source];
    self.navigationItem.title = self.recommend.name;
    
    [self.imageView.layer removeAnimationForKey:@"basicAnimation"];
    self.imageView.layer.beginTime = 0;
    //初始化时间偏移量
    self.imageView.layer.timeOffset = 0;
    //设置动画速度
    self.imageView.layer.speed = 0;
    [self.imageView.layer removeAllAnimations];
    //通过改变view的transform属性值中的z轴坐标来实现旋转
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.recommend.pic]];

    
    
//    [ZQW_AppTools getMessage:string Block:^(id result) {
//        
//        NSMutableDictionary *dictionary = result;
//        PlayData *playData = [[PlayData alloc] init];
//        [playData setValuesForKeysWithDictionary:dictionary];
//        self.playData = playData;
//        //        [playData release];
//        
//        //播放音频url
//        [self.player play:playData.playUrl64];
//        
//        //标题滚动
//        self.navigationItem.title = playData.title;
//        self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 350 , 30 )];
//        self.scrollView.contentSize = CGSizeMake(600 , 0);
//        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.scrollView.contentSize.width, 30 )];
//        [self.scrollView addSubview:label];
//        //        [_scrollView release];
//        self.scrollView.userInteractionEnabled = NO;
//        label.text = playData.title;
//        label.textAlignment = NSTextAlignmentCenter;
//        self.navigationItem.titleView = self.scrollView;
//        //        [self.imageView.layer removeAnimationForKey:@"basicAnimation"];
//        //        self.imageView.layer.beginTime = 0;
//        //        //初始化时间偏移量
//        //        self.imageView.layer.timeOffset = 0;
//        //        //设置动画速度
//        //        self.imageView.layer.speed = 0;
//        //        [self.imageView.layer removeAllAnimations];
//        //通过改变view的transform属性值中的z轴坐标来实现旋转
//        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.coverImage]];
//        //titleView定时器
//        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
//    } and:^(id result1) {
//        
//        
//    }];
    
}


-(void)progressSender{
    
    self.playSlider.maximumValue = self.player.duration;//音乐总共时长
    self.playSlider.value = self.player.progress;//当前进度
    
    //当前时长进度progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.currentTime.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
    NSLog(@"proMin = %ld proSec = %ld",proMin, proSec);
    
    //NSLog(@"tongzhuohao2=============");
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
